package cn.leida.ruoyi.generator.dao;

import cn.leida.ruoyi.common.core.dao.BaseDao;
import cn.leida.ruoyi.common.utils.StringUtils;
import cn.leida.ruoyi.generator.domain.GenTable;
import cn.leida.ruoyi.generator.dto.GenTableDto;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class GenTableDaoCustomImpl extends BaseDao implements GenTableDaoCustom {

    @Override
    public Page<GenTable> findDbTableList(GenTable req, Pageable pageable) {
        // 总数
        ArrayList<Object> params = new ArrayList<>();
        String countSql = findDbTableSql(req, params, true);
        long total = queryCount(countSql, params);
        if (total <= 0) {
            return Page.empty();
        }
        // 数据列表
        List<Object> listParams = new ArrayList<>();
        String listSql = findDbTableSql(req, listParams, false);
        List<JSONObject> jsonObjectList = queryData(listSql, listParams, pageable);
        List<GenTable> dataList = GenTableDto.loadBeans(jsonObjectList);
        return new PageImpl<>(dataList, pageable, total);
    }

    @Override
    public List<GenTable> findDbTableListByNames(List<String> tableNames) {
        List<Object> listParams = new ArrayList<>();
        StringBuilder sql = new StringBuilder();
        sql.append(baseSql());
        if (null != tableNames && !tableNames.isEmpty()) {
            sql.append(" and table_name in (");
            sql.append(tableNames.stream().map(tagCode -> "?").collect(Collectors.joining(",")));
            sql.append(" )");
            listParams.addAll(tableNames);
        }
        String listSql = sql.toString();

        List<JSONObject> jsonObjectList = queryData(listSql, listParams);
        return GenTableDto.loadBeans(jsonObjectList);
    }

    private String baseSql() {
        String baseSql = """
            select
            	table_name as tableName,
            	table_comment as tableComment,
            	create_time as createTime,
            	update_time as updateTime
            from
            	information_schema.tables
            where
            		table_schema = (select database())
            		and table_name not like 'qrtz_%'
            		and table_name not like 'gen_%'
            		and table_name not like 'sys_%'
            		and table_name not in (select table_name from gen_table)
                        
            """;
        return baseSql;
    }


    private String findDbTableSql(GenTable req, List<Object> params, boolean count) {
        StringBuilder sql = new StringBuilder();
        if (count) {
            sql.append(" select count(*) from ( ");
        }
        // 基础sql
        sql.append(baseSql());
        if (StringUtils.isNotBlank(req.getTableName())) {
            sql.append("   AND lower(table_name) like ? ");
            params.add("%" + req.getTableName().toLowerCase() + "%");
        }
        if (StringUtils.isNotBlank(req.getTableComment())) {
            sql.append("   AND lower(table_comment) like ? ");
            params.add("%" + req.getTableComment().toLowerCase() + "%");
        }
        if (null != req.getParams().get("beginTime")) {
            sql.append("   AND date_format(create_time,'%y%m%d') >= date_format(?,'%y%m%d') ");
            params.add(req.getParams().get("beginTime"));
        }
        if (null != req.getParams().get("endTime")) {
            sql.append("   AND date_format(create_time,'%y%m%d') <= date_format(?,'%y%m%d') ");
            params.add(req.getParams().get("endTime"));
        }
        if (!count) {
            sql.append(" order by create_time desc ");
        } else {
            sql.append(" ) query_tmp ");
        }
        return sql.toString();
    }

}
